package com.upsuns.transfer;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 *@Description:<p>文件发送终端</p>
 *@author 王旭
 *@time 2016-1-30 下午5:48:55
 */
public class ClientTerminal implements Terminal {
	
	
	private String address; //接收端地址
	
	private int port; //接收端端口
	
	private SocketChannel socketChannel;
	
	
	public ClientTerminal(String address, int port) {
		this.address = address;
		this.port = port;
		try {
			socketChannel = SocketChannel.open();
			socketChannel.configureBlocking(true);
			socketChannel.connect(new InetSocketAddress(this.address, this.port));
		} catch (IOException e) {
			System.out.println("连接失败");
			e.printStackTrace();
		}
	}
	
	
	
	@Override
	public void send(RandomAccessFile raf, long start, long len) throws IOException {
		
		//采用内存文件映射
		FileChannel fileChannel = raf.getChannel();
		MappedByteBuffer mappedBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, start, len);
		//mappedBuffer.flip(); //准备读缓冲区
		
		socketChannel.write(mappedBuffer);
		
		fileChannel.close();
		socketChannel.close();
		
	}

	@Override
	public void receive(RandomAccessFile raf, long start, long len) {
		
	}
	
	public boolean isConnected() {
		return socketChannel.isConnected();
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
	
	public SocketChannel getSocket() {
		return socketChannel;
	}


	public void setSocket(SocketChannel socketChannel) {
		this.socketChannel = socketChannel;
	}
	
}
